import React, { useState, useEffect } from "react";
import { List, message, Collapse, Spin, ConfigProvider } from "antd";
import { getCrmMailmergeList,groupByAndSum,groupBy,getCrmRecordById,numberToEnglish ,formatDateToUpper} from "../../util/util";

const { Panel } = Collapse;

//通用打印预览
const App = () => {
  // const [templatesList, setTemplatesList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedRow, setSelectedRow] = useState(null);
  const [groupedTemplates, setGroupedTemplates] = useState({
    "报关-分页": [
      {
        id: 422222221,
        name: "报关-报关发票",
        isdep: true,
        isgroup:true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/6oi1d4d475702b5094a8daaccb2c2b377a598?x-cli-msg={"linkId":"1nHCl5jqnKN-31RIu","isFileOwner":false,"version":"5.0"}`,
      },{
        id: 422222222,
        name: "报关-报关箱单-顽皮箱单",
        isdep: true,
        isgroup:true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthr0bc8338d39ad4bddb3de5b5313e0ea12?x-cli-msg={"linkId":"1nHCl5jqpjz-31RIu","isFileOwner":false,"version":"1.0"}`,
      }
    ]
  });

  let Entityname = window.wdata?.Entity;
  let dataid = window.wdata?.EntityId;

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await getCrmMailmergeList(Entityname);
        console.log("response", response);
        if (
          response &&
          response.details &&
          response.details.statusMessage &&
          response.details.statusMessage.templates
        ) {
          const templatesArray = response.details.statusMessage.templates
            .filter((item) => item.folder.name !== "停用")
            .map((item) => ({
              ...item,
              filename: item.name.replace(/\.zdoc$/, ""),
            }));
          console.log("templatesArray", templatesArray);

          // 更新面板的默认展开 key
          const tempGroupedTemplates = templatesArray.reduce((acc, item) => {
            const folderName = item.folder.name;
            if (!acc[folderName]) {
              acc[folderName] = [];
            }
            acc[folderName].push(item);
            return acc;
          }, {});
          console.log('tempGroupedTemplates',tempGroupedTemplates);

          console.log('groupedTemplates',groupedTemplates);
          setGroupedTemplates((prevState) => ({
            ...prevState,
            ...tempGroupedTemplates,
          }));
        }
      } catch (error) {
        console.error("Error fetching data:", error);
      } finally {
        setLoading(false);
      }
    };
    const initialize = async () => {
      await window.zohoReadyPromise;
      console.log("ZOHO is ready", window.ZOHO);
      fetchData();
    };
    initialize();
  }, [Entityname, dataid]);

  const depprint = async (record) => {
    try {
      var recorddata = await getCrmRecordById(Entityname,dataid);

      console.log('recorddata',recorddata);
      if(recorddata){
        let accountid = recorddata.Account?.id;
        let shipperinformationid = recorddata.ShipperInformation?.id;
        let accountinfos = await window.ZOHO.CRM.API.getRecord({
          Entity: "Accounts",
          approved: "both",
          RecordID: accountid,
        });
        let shipperinformations = await window.ZOHO.CRM.API.getRecord({
          Entity: "ShipperInformation",
          approved: "both",
          RecordID: shipperinformationid,
        });
        let accountinfo = accountinfos?.data[0];
        let shipperinformation = shipperinformations?.data[0];
        console.log("accountinfo", accountinfo);
        console.log("shipperinformation", shipperinformation);
        let dcm = await getCrmRecordById("Documentmag",recorddata?.DocumentmagName?.id);
        console.log("dcm", dcm);


        let DeclarationSubfrom = recorddata.DeclarationSubfrom	;
        console.log('DeclarationSubfrom',DeclarationSubfrom);
        if (DeclarationSubfrom.length > 0) {
          const groupjson = groupBy(
            DeclarationSubfrom,
            ["DeclarationcontractNo"],
            "DeclarationSubfrom"
          ); 
          console.log('groupjson',groupjson);


          var groupjson_new = groupByAndSum(groupjson,['CustomsdeclarationName'],['TotalNetWeight','TotalGrossWeight','Qty','DeclarationAmount','TotalVolume']);
          // console.log("groupjson_new", groupjson_new);

          groupjson_new.forEach((item) => {
            item.China_Name = shipperinformation.China_Name || "";
            item.Name_En = shipperinformation.Name_En || "";
            item.Address_En = shipperinformation.Address_En || "";
            item.FullName = accountinfo.FullName || "";
            item.Addressfordocuments = accountinfo?.Addressfordocuments || "";
            item.paymentAmount = numberToEnglish(item.DeclarationAmount_sum || 0);
            item.CustomDate = formatDateToUpper(recorddata.CustomDate);
            item.invno = dcm?.Name|| "";
            item.ShippingPort = dcm?.ShippingPort?.name || "";
            item.DestinationPort = dcm?.DestinationPort?.name || "";
            item.ForeignsacontractNo = dcm?.ForeignsacontractNo|| "";
            item.ShippingMarkAll = dcm?.ShippingMarkAll|| "";
            item.AllContractItem = dcm?.AllContractItem|| "";
            item.TransactionMethod = dcm?.TransactionMethod|| "";
            item.PayMethod = dcm?.PayMethod|| "";
            item.Currency = dcm?.Currency|| "";
            item.AccountOrderNo = dcm?.AccountOrderNo|| "";
            item.shipmentTerms = dcm?.shipmentTerms|| "";


          });
          console.log('groupjson_new',groupjson_new);
          let postData = {
            data: {
              info: {
                id: dataid,
                templateUrl: record.templateurl,
              },
              data: groupjson_new,
            },
          };
          console.log("postData", postData);

          let req_data = {
            arguments: JSON.stringify(postData),
          };
          var result = await window.ZOHO.CRM.FUNCTIONS.execute(
            "printinterfaceagent",
            req_data
          );
          console.log("result", result);
          if (
            result &&
            result.code &&
            result.code.toString() === "success" &&
            result.details &&
            result.details.output
          ) {
            var output = JSON.parse(result.details.output);
            if (output.code && output.code.toString() === "200") {
              var base64data = output.data;
              var byteCharacters = atob(base64data);
              var byteNumbers = new Array(byteCharacters.length);
              for (var i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
              }
              var byteArray = new Uint8Array(byteNumbers);

              var blob = new Blob([byteArray], { type: "application/pdf" });
              var blobUrl = window.URL.createObjectURL(blob);
              window.open(blobUrl, "_blank");
            } else {
              message.error("发生错误，请联系管理员！");
            }
          }

        }else {
          message.warning("此条数据没有行明细数据，请核对后再进行操作！");
        }
      }else {
        message.error("获取页面数据失败！");
      }
    }catch (error) {
      message.error(`Failed to open PDF: ${error.message}`);
      console.error("Error fetching PDF:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleClick = async (record) => {
    setLoading(true);
    try {
      if (record?.isdep && record?.isgroup ) {
        await depprint(record);
      }else if(record?.isdep && !record?.isgroup){
        




      } else {
        var filename = `${record.filename}${dataid}.pdf`;
        let req_data_a = {
          arguments: JSON.stringify({
            entityname: Entityname,
            dataid: dataid[0],
            templateid: record.id,
            filename: filename,
          }),
        };

        const filedata = await window.ZOHO.CRM.FUNCTIONS.execute(
          "mailmergeshow",
          req_data_a
        );

        if (filedata && filedata.details && filedata.details.output) {
          var strdata = filedata.details.output;
          var jsondata = JSON.parse(strdata);
          var pdfurl = jsondata?.data[0].attributes?.Permalink;
          console.log(pdfurl);
          // 提取文件 ID
          const fileId = pdfurl.split("/").pop();

          // 构建新的 URL
          const printurl = `https://workdrive.zoho.com.cn/print/${fileId}`;
          window.open(printurl, "_blank");
        }
      }
    } catch (error) {
      message.error(`Failed to open PDF: ${error.message}`);
      console.error("Error fetching PDF:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <ConfigProvider
    theme={{
      components: {
        Collapse: {
          contentPadding: "4px 14px"
        },
      }
    }}
    >
    <div style={{ position: "relative", minHeight: "100vh" }}>
      {loading ? (
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            height: "100vh",
          }}
        >
          <Spin />
        </div>
      ) : (
        <Collapse accordion defaultActiveKey={[0]}>
          {Object.keys(groupedTemplates).map((folderName, index) => (
            <Panel header={folderName} key={index}>
              <List
                dataSource={groupedTemplates[folderName]}
                renderItem={(item) => (
                  <List.Item
                    onClick={() => handleClick(item)}
                    style={{
                      cursor: "pointer",
                      fontSize: "15px",
                      display: "flex",
                      alignItems: "center",
                      height: "35px",
                      backgroundColor:
                        item.id === selectedRow ? "#e6f7ff" : "transparent",
                    }}
                    onMouseEnter={() => setSelectedRow(item.id)}
                    onMouseLeave={() => setSelectedRow(null)}
                  >
                    {item.isdep ? item.name : item.filename}
                  </List.Item>
                )}
              />
            </Panel>
          ))}
        </Collapse>
      )}
    </div>
    </ConfigProvider>
  );
};

export default App;
